//
//  Phase.swift
//  eat_known
//
//  Created by 心情 on 2018/7/26.
//  Copyright © 2018年 心情. All rights reserved.
//

import Foundation
import HandyJSON

enum PhaseFoodState: String, HandyJSONEnum {
    case Unknown   = "未知"
    case OK        = "能吃"
    case Warn      = "慎吃"
    case Forbidden = "不能吃"
    
    static func name(_ text: String) -> PhaseFoodState {
        switch text {
        case "能吃":
            return .OK
        case "慎吃", "少吃":
            return .Warn
        case "不能吃":
            return .Forbidden
        default:
            return .Unknown
        }
    }
    
    func icon() -> UIImage? {
        switch self {
        case .OK:
            return UIImage(named: "icon_ok")
        case .Warn:
            return UIImage(named: "icon_warn")
        case .Forbidden:
            return UIImage(named: "icon_error")
        default:
            return nil
        }
    }
}

enum PhaseState: String, HandyJSONEnum {
    case Unknown     = "未知"
    case Preg        = "怀孕"
    case Nurse       = "坐月子"
    case Feed        = "哺乳"
    case Baby        = "婴儿"
    
    static func name(_ text: String) -> PhaseState {
        switch text {
        case "怀孕", "孕妇", "1":
            return .Preg
        case "坐月子", "2":
            return .Nurse
        case "哺乳", "3":
            return .Feed
        case "婴儿", "4":
            return .Baby
        default:
            return .Unknown
        }
    }
}

class Phase: HandyJSON {
    var state: PhaseState = .Unknown
    var source: FoodSource = .LadyBird //须在 foodState 之前，解析时优先解析 source
    var foodState: PhaseFoodState = .Unknown
    
    required init() {
    }
    
    init(state: PhaseState, foodState: PhaseFoodState) {
        self.state = state
        self.foodState = foodState
    }
    
    func mapping(mapper: HelpingMapper) {
        
        mapper <<< source <-- ("eatable", TransformOf<FoodSource, Int>(
            fromJSON: { (eatable) -> FoodSource? in
                return FoodSource.AliPay
        },
            toJSON: { (foodSource) -> Int? in
                return 0
        }))

        mapper <<< foodState <-- (["type", "eatable"], TransformOf<PhaseFoodState, Any>(
            fromJSON: { (type: Any?) -> PhaseFoodState? in
                if self.source == .AliPay {
                    let realType = type as! Int
                    return PhaseFoodState.aliPay(realType)
                } else {
                    let realType = type as! Int
                    return PhaseFoodState.ladyBird(realType)
                }
        },
            toJSON: { (type: PhaseFoodState?) -> String? in
                return type!.rawValue
        }))
        
        mapper.specify(property: &state, name: "period") { (period) -> PhaseState in
            return PhaseState.name(period)
        }
    }

}
